package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnums;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.Feign.MemberFeignService;
import com.atguigu.gulimall.auth.Feign.ThirdPartFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: gulimall
 * @description:
 * @author: 江天赐
 * @create: 2022-08-10 20:35
 */
@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/msm/send")
    R sendCode(@RequestParam("phone") String phone) {
        //1.接口防刷
        //2.验证码再次校验//在第三方服务中已经将验证码放到redis中2分钟过期
        String code = stringRedisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            long l = Long.parseLong(code.split("_")[1]);
            if (System.currentTimeMillis() - l < 120000) {
                return R.error(BizCodeEnums.MSM_CODE_EXCEPTION.getCode(), BizCodeEnums.MSM_CODE_EXCEPTION.getMsg());
            }
        }
        thirdPartFeignService.sendCode(phone);
        return R.ok();
    }

    /**
     * TODO:重定向携带数据，利用session，将数据存到session，
     * 只要跳到下一个页面，取出这个数据，session的数据会被删掉
     * <p>
     * //TODO：分布式session
     *
     * @param vo
     * @param result
     * @param redirectAttributes 模拟重定向携带数据
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Validated UserRegistVo vo, BindingResult result,
                         RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {//forward 转发请求
//            Map<String, String> errors = new HashMap<>();
//            result.getFieldErrors().stream().map(item -> {
//                String field = item.getField();
//                String defaultMessage = item.getDefaultMessage();
//                errors.put(field, defaultMessage);
//            });
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            //校验出错，转发到注册页
            redirectAttributes.addFlashAttribute("errors", errors);
            //Model model  model.addAttribute("errors", errors)
            //Request method 'POST' not supported
            //用户注册->regist【post】--->转发/reg.html(路径映射默认是get方式)
            // 所以直接return "reg";表单会重复提交，使用重定向 模拟session 上次表单的提示数据将会删除
//            httpSession.setAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //真正注册
        //校验验证码
        String code = vo.getCode();
        String s = stringRedisTemplate.opsForValue().get(vo.getPhone());
        if (!StringUtils.isEmpty(s) && code.equals(s.split("_")[0])) {
            //验证码通过, 真正注册调用远程服务,令牌机制(验证完直接删除)
            stringRedisTemplate.delete(vo.getPhone());
            //
            R r = memberFeignService.regist(vo);
            if (r.getCode() == 0) {//成功
                return "redirect:http://auth.gulimall.com/login.html";
            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("msg", r.getData(new TypeReference<String>() {
                }));
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session) {

        //远程登录
        R login = memberFeignService.login(vo);
        if (login.getCode() == 0) {
            //成功
            MemberRespVo data = login.getData("data", new TypeReference<MemberRespVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            return "redirect:http://gulimall.com";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", login.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute == null) {
            return "login";
        } else {
            return "redirect:http://gulimall.com";
        }

    }
}
